; docformat = 'rst'
;
;+
;
; :Purpose:
;   Calculate correlation matrix from full covariance matrix
;
; :Inputs:
;   Covariance: (Input, required) Covariance matrix
;
; :Outputs:
;   Correlation matrix (normalised covariance matrix):
;     R_ij=P_ij/(sqrt(P_ii)sqrt(P_jj))
;
; :Example::
;   IDL> covariance=[[2., -0.5], [-0.5, 2.]]
;   IDL> print, covariance
;     2.00000    -0.50000
;    -0.50000      2.00000
;   IDL> correlation=mr_correlation_matrix(covariance)
;   IDL> print, correlation
;     1.00000    -0.250000
;    -0.250000      1.00000
;
; :History:
; 	Written by: Matt Rigby, University of Bristol, Jul 16, 2013
;
;-
function mr_correlation_matrix, covariance

  nStates=n_elements(covariance[0, *])

  correlation=covariance
  diag=sqrt(diag_matrix(covariance))
  
  for di=0, nStates-1 do begin
    correlation[di, *]=correlation[di, *]/diag[di]
    correlation[*, di]=correlation[*, di]/diag[di]
  endfor

  return, correlation

End